package com.hits.buildqrcode.service;

import com.hits.buildqrcode.config.HttpClient;
import com.hits.buildqrcode.domian.ParamApp;
import com.hits.buildqrcode.mapper.SfjdSldjMapper;
import com.hits.buildqrcode.util.SpringUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author ly
 * @Date 2021/6/8 10:37
 * @Version 1.0
 */
@Service
public class TokenService implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(TokenService.class);

    @Autowired
    private CaseService caseService;

    @Autowired
    private SfjdSldjMapper sfjdSldjMapper;

    public static String token;

    /**
     * 功能描述：获取token
     */
    public static void getTokenToInterFace() {
        /* 将对象转换为json字符串 */
        ParamApp bean = SpringUtil.getBean(ParamApp.class);
        String param = JSONObject.fromObject(bean).toString();
        try {
            /* 请求返回token接口 */
            String tokenToInterFace = HttpClient.getTokenToInterFace(param);
            /* 将json字符串转json对象 */
            JSONObject jsonObject = JSONObject.fromObject(tokenToInterFace);
            token = (String) jsonObject.get("data");
            logger.info("状态为:" + jsonObject.get("code") + "" + jsonObject.get("message"));
        } catch (IOException e) {
            logger.error("获取token异常:" + e.getMessage());
        }
    }

    /**
     * 功能描述:每五分钟获取案件数据请求接口
     * 获取二维码插入鉴定意见书中
     */
    @Scheduled(cron = "0 0/3 * * * ?")
    public void timingInsertCode() {
        try {
            /*有无案件*/
            int countAj = sfjdSldjMapper.getCountAj();
            if (countAj > 0) {
                com.alibaba.fastjson.JSONObject jsonObject = caseService.getQrCodeDateByInfo();
                if (jsonObject.size()>0){
                    String message = (String) jsonObject.get("message");
                    if ( message.equals("无效的token")){
                        return;
                    }
                }else {
                    return;
                }
            } else {
                TimeUnit.HOURS.sleep(1);
            }
        } catch (Exception e) {
            logger.error("获取二维码定时任务异常:" + e.getMessage());
        }

    }

    /**
     * 启动时自动执行一次获取token
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        getTokenToInterFace();
        if (token != null && !token.equals("")) {
            timingInsertCode();
        }
    }
}
